package com.main.usermanagement.interfaces.assembler;

import com.main.common.base.base.BaseAssembler;
import com.main.common.base.base.BaseAssemblerFactory;
import com.main.usermanagement.domain.user.aggregate.User;
import com.main.usermanagement.domain.user.entity.UserAddress;
import com.main.usermanagement.domain.user.entity.UserInfo;
import com.main.usermanagement.interfaces.dto.UserAddressDTO;
import com.main.usermanagement.interfaces.dto.UserDTO;
import com.main.usermanagement.interfaces.dto.UserInfoDTO;
import jakarta.validation.constraints.NotNull;

import java.util.ArrayList;
import java.util.List;

public class UserAssembler {
    private final BaseAssembler<User, UserDTO> baseAssembler;
    private final BaseAssembler<UserInfo, UserInfoDTO> baseUserInfoAssembler;
    private final BaseAssembler<UserAddress, UserAddressDTO> baseUserAddressAssembler;

    public UserAssembler(@NotNull BaseAssemblerFactory baseAssemblerFactory) {
        this.baseAssembler = baseAssemblerFactory.getService(UserDTO.class);
        this.baseUserInfoAssembler = baseAssemblerFactory.getService(UserInfoDTO.class);
        this.baseUserAddressAssembler = baseAssemblerFactory.getService(UserAddressDTO.class);
    }

    public UserDTO toDTO(User user) {
        UserDTO userDTO = new UserDTO();
        userDTO = baseAssembler.toDTO(user, userDTO);
        userDTO.setName(user.getName());
        userDTO.setPhone(user.getPhone());
        userDTO.setPhoneCode(user.getPhoneCode());
        userDTO.setEmail(user.getEmail());
        userDTO.setWechat(user.getWechat());
        userDTO.setDirectSupervisorId(user.getDirectSupervisorId());
        userDTO.setOrganizationAtomicId(user.getOrganizationAtomicId());
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        UserInfo userInfo = user.getUserInfo();
        userInfoDTO = baseUserInfoAssembler.toDTO(userInfo, userInfoDTO);
        userInfoDTO.setGender(userInfo.getGender());
        userInfoDTO.setBirthDate(userInfo.getBirthDate());
        userInfoDTO.setIdCard(userInfo.getIdCard());
        userDTO.setUserInfo(userInfoDTO);
        UserAddress userAddress = userInfo.getAddress();
        UserAddressDTO userAddressDTO = new UserAddressDTO();
        userAddressDTO = baseUserAddressAssembler.toDTO(userAddress, userAddressDTO);
        userDTO.setUserAddress(userAddressDTO);
        return userDTO;
    }

    public List<UserDTO> toDTOs(List<User> userList) {
        List<UserDTO> userDTOList = new ArrayList<>();
        for (User entity : userList) {
            UserDTO userDTO = new UserDTO();
            userDTO = baseAssembler.toDTO(entity, userDTO);
            userDTOList.add(userDTO);
        }
        return userDTOList;
    }

}